package com.sacc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.power.common.model.CommonResult;
import com.sacc.mapper.ArticleMapper;
import com.sacc.pojo.Article;
import com.sacc.service.ArticleService;
import com.sacc.util.FileUtil;
import com.sacc.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 滚~韬
 * @date 2022/4/19 16:55
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
//    @Autowired
//    private FileUtil fileUtil;

    /**
     * 获取资讯文章列表
     * @param count
     * @return
     */
    @Override
    public List<Article> GetArticleList(Integer count) {
        Page<Article> articlePage = articleMapper.selectPage(new Page<>(count, 8),
                new QueryWrapper<Article>()
                    .select("id","title","author","keywords","description","image_url"));
        List<Article> records = articlePage.getRecords();
        return records;
    }

    /**
     * 根据资讯文章id获取文章
     * @param id
     * @return
     */
    @Override
    public Article GetArticle(Integer id) throws IOException {
        Article article = articleMapper.selectById(id);
        article.setImageUrl(FileUtil.getFile(article.getImageUrl()));
        return articleMapper.selectById(id);
    }

    /**
     * 根据资讯文章id删除文章
     * @param id
     * @return
     */
    @Override
    public CommonResult DeleteArticle(Integer id) {
        try {
            articleMapper.deleteById(id);
            return new CommonResult(true,"删除成功:",id);
        }catch (Exception e){
            return new CommonResult(false,"删除失败:"+e.toString(),id);
        }
    }

    /**
     * 添加资讯文章
     * @param article
     * @return
     */
    @Override
    public CommonResult AddArticle(Article article, MultipartFile file) {
        try{
//            String image = fileUtil.upload("/article/",file,"image");
            CommonResult upload = OssUtil.Upload(file);
            article.setCreateTime(LocalDateTime.now());
            article.setImageUrl((String) upload.getData());
            articleMapper.insert(article);
            return new CommonResult(true,"插入成功",article);
        }catch (Exception e){
            return new CommonResult(false,"插入失败:"+e.toString(),article);
        }
    }
}
